<template>
  <form-arr-header :config="scope.config"><template slot="after_begin"><div class="table-like-arr__th">
    <el-checkbox class="table-like-arr__ck" :disabled="disabled" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange(scope, $event)"></el-checkbox>
    #</div></template>
  </form-arr-header>
</template>

<script>
export default {
  name: "FormCheckedAll",
  props: [
      'scope'
  ],
  inject: ['form_aaa', 'zformLoader'],
  data() {
    return {
      disabled: false,
      isIndeterminate: false,
      checkAll: false
    }
  },
  mounted() {
    // console.log(this.form_aaa)
    this.form_aaa.mitt.on('tr-change', this.handle)
    this.form_aaa.mitt.on('arr-change', this.handleArr)
    this.form_aaa.mitt.on('clear-all', this.handleC)
  },
  beforeDestroy() {
    this.form_aaa.mitt.off('tr-change', this.handle)
    this.form_aaa.mitt.off('arr-change', this.handleArr)
    this.form_aaa.mitt.off('clear-all', this.handleC)
  },
  methods: {
    handleC() {
      this.isIndeterminate = false
      this.checkAll = false
    },
    getCheckedAll() {
      let model =  this.zformLoader.getCurIns().getModel()
      let arr = ZY.lodash.get(model, this.scope.pathArr);
      let checkedCount = this.form_aaa.getCheck().filter(v => v).length;
      // console.log(arr, this.form_aaa.getCheck())
      let obj = {}
      obj.isIndeterminate = checkedCount > 0 && checkedCount < arr.length;
      // console.log(arr, this.form_aaa.getCheck())
      obj.checkAll = checkedCount === arr.length;
      if (arr.length < 1) {
        obj.checkAll = false
      }
      return obj
    },
    handle() {
      let model = this.getCheckedAll()
      // console.log('handle', model)
      this.isIndeterminate = model.isIndeterminate
      this.checkAll = model.checkAll
    },
    handleArr({}) {
      let model =  this.zformLoader.getCurIns().getModel()
      let arr = ZY.lodash.get(model, this.scope.pathArr);
      let checkedCount = this.form_aaa.getCheck().filter(v => v).length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < arr.length;
      // console.log(arr, this.form_aaa.getCheck())
      this.checkAll = checkedCount === arr.length;
      if (arr.length < 1) {
        this.checkAll = false
        this.disabled = true
      } else {
        this.disabled = false
      }
    },
    handleCheckAllChange(scope, val) {
      let model =  this.zformLoader.getCurIns().getModel()
      let arr = ZY.lodash.get(model, scope.pathArr);
      // this.checkedCities = val ? [] : [];
      this.isIndeterminate = false;
      // console.log('handleCheckAllChange',  this.model)
      this.form_aaa.setCheck( val ? arr.map(v => true) : [] , scope )
      this.form_aaa.reload()
      this.form_aaa.mitt.emit('all-change', {

      })
    },
  }
}
</script>

<style scoped>

</style>
